package com.youbug.mall.pms.service.impl;

import com.youbug.common.exception.WrongStatusException;
import com.youbug.mall.pms.entity.Category;
import com.youbug.mall.pms.mapper.CategoryMapper;
import com.youbug.mall.pms.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品三级分类 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2023-05-07
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    private List<Category> cache;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> listWithTree() {
        if(!CollectionUtils.isEmpty(cache)){
            return cache;
        }
        //1、查询出所有分类
        List<Category> entities = this.list();
        //2、组装成父子的树形结构
        //2.1)、找到所有一级分类
        List<Category> levelMenus = entities.stream()
                .filter(e -> e.getParentCid() == 0)
                .peek((menu) -> menu.setChildren(getChildrens(menu, entities)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        cache = levelMenus;
        return levelMenus;
    }

    @Override
    public boolean deleteById(Long id) {

        Category category = categoryMapper.hasChildrenById(id);
        if(!ObjectUtils.isEmpty(category)){
            throw new WrongStatusException("含有子种类无法删除");
        }

        boolean remove = this.removeById(id);

        return remove;
    }

    @Override
    public boolean addCategory(Category category) {

        boolean save = this.save(category);

        return save;
    }

    @Override
    public void cleanCache(boolean result) {
        if(result){
            this.cache = null;
        }
    }


    //递归查找所有菜单的子菜单
    private List<Category> getChildrens(Category root, List<Category> all) {

        List<Category> children = all.stream().filter(category -> {
            return category.getParentCid().equals(root.getCatId());
        }).peek(category -> {
            //1、找到子菜单(递归)
            category.setChildren(getChildrens(category, all));
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        return children;

    }
}
